const M=require("ming_node");
const fs=require("fs");

class HotServerPlugin {

    constructor({dirList=["static"],onlySelfDefine=false}) {
        this.dirList=dirList;
        this.onlySelfDefine=onlySelfDefine;
    }
    install(app,args){
        const sseApp=M.sseServer();
        app.get("/sseServer",sseApp)
        let r=this.dirList;
        if(this.onlySelfDefine==false){
            if(fs.existsSync("public")){
                r= M.getFileDirList("./public");
                r.push("public")
            }
            if(fs.existsSync("views")){
                let r1= M.getFileDirList("./views");
                r=[...r,...r1,"views"]
            }
            if(fs.existsSync("static")){
                let  r1= M.getFileDirList("./static");
                r=[...r,...r1,"static"]
            }
            r.push(".");
        }
        r=Array.from(new Set(r))
        r.forEach(u=>{
            M.watchFile(u,({file,event})=>{
                if(event=="change"){
                    // console.log(file,event);
                    sseApp.send("change");
                }
            })

        })
        console.log("watch on ",r)
    }

}

module.exports =  HotServerPlugin;

